package com.changgou.order.mq.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Map;

@Component
@RabbitListener(queues = "${mq.pay.queue.order}")
public class OrderMessageListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService orderService;

    /**
     * 支付结果监听
     * @param msg
     */
    @RabbitHandler
    public void getMessage(String msg) throws ParseException {
        Map<String,String> resultMap = JSON.parseObject(msg, Map.class);
        //通信标识
        String return_code=resultMap.get("return_code");
        if("SUCCESS".equals(return_code)){
            //业务结果
            String result_code = resultMap.get("result_code");
            //订单号
            String out_trade_no=resultMap.get("out_trade_no");
            if ("SUCCESS".equals(result_code)){
                //支付成功,修改订单
                orderService.updateStatus(out_trade_no,resultMap.get("time_end"),resultMap.get("transaction_id"));
            }else {
                //支付失败,通知微信关闭支付,取消订单,回滚库存
                orderService.deleteOrder(out_trade_no);
            }
        }


    }
}
